<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { FormInstance, UploadProps, UploadUserFile } from 'element-plus';
import { $t } from '@/plugins/i18n';
import ReCol from '@/components/MyCol';
import { useAdminUserStore } from '@/store/system/adminUser';
import { message } from '@/utils/message';
import { deptSelector } from '@/views/system/dept/utils/columns';
import { deptList } from '@/views/system/adminUser/utils/hooks';

const adminUserStore = useAdminUserStore();

const formRef = ref<FormInstance>();
const fileList = ref<UploadUserFile[]>([]);

// 修改部门选择器配置
const deptProps = {
	...deptSelector,
	// 确保ID被正确传递而不是路径
	emitPath: false,
	// 可以选择任意级别的节点
	checkStrictly: true,
};

const form = reactive({
	deptId: '',
	file: null as File | null
});

const rules = {
	deptId: [
		{ required: true, message: '部门' + $t('required'), trigger: 'change' }
	],
	file: [
		{ required: true, message: '文件' + $t('required'), trigger: 'change' }
	]
};

// 文件上传前的处理
const beforeUpload: UploadProps['beforeUpload'] = file => {
	// 检查文件类型
	const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
					file.type === 'application/vnd.ms-excel';
	if (!isExcel) {
		message('只能上传Excel文件', { type: 'error' });
		return false;
	}
	
	// 限制文件大小, 10MB
	const isLt10M = file.size / 1024 / 1024 < 10;
	if (!isLt10M) {
		message('文件大小不能超过10MB', { type: 'error' });
		return false;
	}
	
	form.file = file;
	return false; // 阻止自动上传
};

// 下载模板
const downloadTemplate = async () => {
	try {
		await adminUserStore.downloadUserImportTemplate();
	} catch (error) {
		message('下载模板失败', { type: 'error' });
	}
};

// 文件变更处理
const handleFileChange: UploadProps['onChange'] = uploadFile => {
	fileList.value = [uploadFile.raw] as UploadUserFile[];
	form.file = uploadFile.raw;
};

// 移除文件
const handleRemove = () => {
	fileList.value = [];
	form.file = null;
};

defineExpose({ formRef, form });
</script>

<template>
	<el-form ref="formRef" :model="form" :rules="rules" label-position="left" label-width="auto">
		<el-row :gutter="30">
			<!-- 选择部门 -->
			<re-col :sm="24" :value="24" :xs="24">
				<el-form-item label="选择部门" prop="deptId">
					<el-cascader 
						v-model="form.deptId" 
						:options="deptList" 
						:placeholder="'请选择部门'" 
						:props="deptProps" 
						class="w-full" 
						clearable 
						filterable
					>
						<template #default="{ node, data }">
							<span>{{ data.deptName }}</span>
							<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
						</template>
					</el-cascader>
				</el-form-item>
			</re-col>
			
			<!-- 文件上传 -->
			<re-col :sm="24" :value="24" :xs="24">
				<el-form-item label="上传文件" prop="file">
					<el-upload
						class="upload-demo w-full"
						:before-upload="beforeUpload"
						:file-list="fileList"
						:auto-upload="false"
						:limit="1"
						accept=".xlsx,.xls"
						:on-change="handleFileChange"
						:on-remove="handleRemove"
					>
						<el-button type="primary">选择文件</el-button>
						<template #tip>
							<div class="el-upload__tip">
								Excel文件格式，大小不超过10MB
							</div>
						</template>
					</el-upload>
				</el-form-item>
			</re-col>
			
			<!-- 下载模板 - 美化版链接形式 -->
			<re-col :sm="24" :value="24" :xs="24">
				<div class="flex justify-center items-center mt-2 py-3 bg-gray-50 rounded-md">
					<el-icon class="mr-2 text-primary"><i-ep-download /></el-icon>
					<a href="javascript:;" class="text-primary hover:text-primary-light transition-colors duration-300 text-sm" @click="downloadTemplate">下载导入模板</a>
					<span class="text-gray-400 text-xs ml-3">（请按照模板格式填写数据）</span>
				</div>
			</re-col>
		</el-row>
	</el-form>
</template>

<style scoped>
.text-primary {
	color: var(--el-color-primary);
}
.text-primary-light {
	color: var(--el-color-primary-light-3);
}
.bg-gray-50 {
	background-color: var(--el-fill-color-lighter);
}
.text-gray-400 {
	color: var(--el-text-color-secondary);
}
</style> 